package com.voucher.qiege.three;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.*;
import org.apache.http.util.EntityUtils;
import java.util.Arrays;
import java.util.List;

public class LoginService {
    
    public static void login(String username, String password) throws Exception {
        // Step 1: 初始化会话并获取JSESSIONID
//        String jsessionId = SessionManager.initSession();
//        System.out.println("[DEBUG] JSESSIONID: " + jsessionId);

        // Step 2: 加密密码
//        String encryptedPassword = PasswordEncryptor.encryptPassword(password, jsessionId);
        String encryptedPassword = "Mx123456";
        System.out.println("[DEBUG] Encrypted Password: " + encryptedPassword);

        // Step 3: 发送登录请求（保持同一CookieStore）

        HttpPost loginRequest = new HttpPost("http://oa.mexingroup.com:9999/j_acegi_security_check");
        List<NameValuePair> params = Arrays.asList(
            new BasicNameValuePair("j_username", username),
            new BasicNameValuePair("j_password", encryptedPassword)
        );
        loginRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        // Step 4: 执行请求并验证结果
        try (CloseableHttpResponse response = SessionManager.httpClient.execute(loginRequest)) {
            String responseHtml = EntityUtils.toString(response.getEntity());
            if (responseHtml.contains("lui_login_message_div")) {
                String error = responseHtml.split("lui_login_message_div")[1]
                                        .split("</div>")[0]
                                        .replaceAll("系统提示：", "")
                                        .trim();
                throw new RuntimeException("登录失败: " + error);
            }
//            System.out.println("登录成功！Current Cookies:\n " +
//                SessionManager.cookieStore.getCookies());
            System.out.println("登录成功！Current Cookies:");
            for (Cookie cookie : SessionManager.cookieStore.getCookies()) {
                System.out.printf("  %-15s: %s%n", "Name", cookie.getName());
                System.out.printf("  %-15s: %s%n", "Value", cookie.getValue());
                System.out.println("  ------------------------------------------------");
            }
        }
    }
}
